package com.mlk.rbac.listener;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mlk.core.config.DeptConfig;
import com.mlk.core.constants.Constant;
import com.mlk.core.util.JSONUtils;
import com.mlk.rbac.mapper.SysDeptMapper;
import com.mlk.rbac.mapper.SysUserMapper;
import com.mlk.rbac.po.SysDept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 部门缓存监听器
 */
@Component
public class DeptListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private SysDeptMapper sysDeptMapper;

    /**
     * 装载数据
     * @param contextRefreshedEvent
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        List<SysDept> depts = this.sysDeptMapper.selectList(new EntityWrapper<>(SysDept.builder().status(Constant.status_ok).build()));

        depts.forEach(dept->{
            redisTemplate.opsForValue().set(DeptConfig.CACHE_PREFIX+dept.getId(), JSONUtils.toJSONString(dept));
        });

    }
}
